//
//  ArrayExtension.swift
//  Intersection
//
//  Created by 我骑着蜗牛走天下 on 2025/3/6.
//

import Foundation

enum JSONError: Error {
    case invalidObject
    case encodingFailed
}

extension JSONError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .invalidObject:
            return "toJSONString 不是Json格式"
        case .encodingFailed:
            return "toJSONString 解析失败"
        }
    }
}

extension Array{
    
    ///数组转json字符串
//    public func toJSONString() -> String {
//        if (!JSONSerialization.isValidJSONObject(self)) {
//            print("无法解析出JSON字符串")
//            return String()
//        }
//        let data = try! JSONSerialization.data(withJSONObject: self, options: [])
//        let JSONString = NSString(data:data,encoding: String.Encoding.utf8.rawValue)
//        return JSONString! as String
//    }
    
    public func toJSONString() throws -> String {
        guard JSONSerialization.isValidJSONObject(self) else {
            throw JSONError.invalidObject
        }
        let data = try JSONSerialization.data(withJSONObject: self, options: [])
        guard let jsonString = String(data: data, encoding: .utf8) else {
            throw JSONError.encodingFailed
        }
        return jsonString
    }
    
    /// 转json格式的data
    public func toJsonData()->Data?{
        
        if (!JSONSerialization.isValidJSONObject(self)) {
            debugLog("ArrayToJsonData 无法解析出JSON")
            return Data()
        }
        do {
            let data : Data = try JSONSerialization.data(withJSONObject: self, options: [])
            return data
        }catch{
            debugLog("ArrayToJsonData 解析失败")
            return nil
        }
        
    }
    
    /// 安全获取数组下标元素
    public subscript(safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
    
    public mutating func safeRemove(at index: Int) {
        if index >= 0 && index < self.count {
            self.remove(at: index)
        } else {
            print("Warning: Index \(index) out of range for array of size \(self.count)")
        }
    }
    
}


extension Array where Element: Codable {
    func toJSONString(outputPretty:Bool = true) -> String? {
        let encoder = JSONEncoder()
        // 美化输出
        if outputPretty {
            encoder.outputFormatting = .prettyPrinted
        }
        guard let data = try? encoder.encode(self) else { return nil }
        return String(data: data, encoding: .utf8)
    }
}




extension Array where Element: Equatable {
    
    /// 存在元素删除，不存在添加
    public mutating func toggleElement(_ element: Element) {
        if let index = firstIndex(of: element) {
            remove(at: index) // 存在则删除
        } else {
            append(element) // 不存在则添加
        }
    }
    
    /// 更新元素
    public mutating func updateElement(_ element: Element) {
        if let index = self.firstIndex(of: element) {
            self[index] = element  // 存在则替换
        } else {
            self.append(element)   // 不存在则添加
        }
    }
    
}
